package com.time.company.components.compose;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.google.gson.Gson;
import com.makeramen.roundedimageview.RoundedImageView;
import com.time.company.R;
import com.time.company.app.AddressManager;
import com.time.company.base.BaseActivity;
import com.time.company.base.BasePW;
import com.time.company.components.MainActivity;
import com.time.company.components.compose.model.MyAlbum;
import com.time.company.components.compose.model.MyBitmap;
import com.time.company.components.popup.DeletePW;
import com.time.company.components.popup.ExitEditPW;
import com.time.company.servermodel.BasicBean;
import com.time.company.utils.NetWorkUtils;
import com.time.company.utils.ScreenUtils;
import com.time.company.utils.ToastUtils;
import com.time.company.utils.string.Constant;
import com.time.company.views.MyGridView;
import com.time.company.webserver.helper.WebServerManager;
import com.time.company.webserver.helper.picasso.PicassoImageLoader;
import com.time.company.webserver.listener.ResponseCallback;
import com.time.company.webserver.request.requestsParamters.ComposeParameters;
import com.yanzhenjie.album.Action;
import com.yanzhenjie.album.Album;
import com.yanzhenjie.album.AlbumFile;
import com.yanzhenjie.album.api.widget.Widget;
import com.yanzhenjie.nohttp.BasicBinary;
import com.yanzhenjie.nohttp.Binary;
import com.yanzhenjie.nohttp.FileBinary;
import com.yanzhenjie.nohttp.Logger;
import com.yanzhenjie.nohttp.NoHttp;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.rest.Request;
import com.yanzhenjie.nohttp.rest.Response;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import java.io.File;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * 编辑
 * Created by Bing on 2017/7/17.
 * E-mail is tx16bing@163.com
 */

public class EditActivity extends BaseActivity
        implements View.OnClickListener, AMapLocationListener {

    private static final int TIME_MAP_REQUEST_CODE = 11;

    // Request and What
    private Request request;
    private static final int COMMIT_DYNAMICS_WHAT = 3;

    private static final String EXTRA_ENTER_TYPE = "extra_enter_type";
    private static String enterType;

    private LinearLayout llParent;
    private ImageView ivBack;
    private TextView tvRelease;
    private EditText etContent;
    private TextView tvLocation;
    private GridView gvPics;

    // Location
    private AMapLocationClient locationRequest;
    private double mLatitude, mLongitude;

    // 窗口背景属性
    private WindowManager.LayoutParams attributes;
    private ExitEditPW exitEditPW;
    private DeletePW deletePW;

    private GridPicAdapter gridPicAdapter;
    public static ArrayList<AlbumFile> mAlbumFiles;

    // 当前地址位置
    private String curLocation;

    // Permission
    private static final int PICTURE_PERMISSION_REQUEST_CODE = 100;
    private static final int LOCATION_PERMISSION_REQUEST_CODE = 102;
    private static final int DENIED_PERMISSION_REQUEST_CODE = 103;

    public static void start(Activity mContext, String enterType) {
        Intent intent = new Intent(mContext, EditActivity.class);
        intent.putExtra(EXTRA_ENTER_TYPE, enterType);
        mContext.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit);
        enterType = getIntent().getStringExtra(EXTRA_ENTER_TYPE);
        assignViews();
        initAdapter();
        andPermission();
    }

    protected void onRestart() {
        gridPicAdapter.updateData();
        super.onRestart();
    }

    private void assignViews() {
        llParent = findView(R.id.ll_edit_publish_parent);
        ivBack = findView(R.id.iv_back);
        tvRelease = findView(R.id.tv_edit_release);
        etContent = findView(R.id.et_release_content);
        gvPics = findView(R.id.gv_release_pics);

        tvLocation = findView(R.id.tv_location);
        LinearLayoutManager lmType = new LinearLayoutManager(this);
        lmType.setOrientation(LinearLayoutManager.HORIZONTAL);

        ivBack.setOnClickListener(this);
        tvRelease.setOnClickListener(this);
        tvLocation.setOnClickListener(this);

    }

    private void andPermission() {
        // 需要调用AndPermission来开启定位权限提示
        AndPermission.with(this)
                .requestCode(LOCATION_PERMISSION_REQUEST_CODE)
                .permission(Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                .callback(listener)
                // rationale作用是：用户拒绝一次权限，再次申请时先征求用户同意，再打开授权对话框；
                // 这样避免用户勾选不再提示，导致以后无法申请权限。
                // 你也可以不设置。
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                        AndPermission.rationaleDialog(EditActivity.this, rationale)
                                .show();
                    }
                })
                .start();
    }

    /**
     * 发送动态
     */
    private void commitRequest() {
        if (NetWorkUtils.isNetAvailable(this)) {
            ComposeParameters parameters = new ComposeParameters();
            parameters.setCommand(getString(R.string.command_publishTopic));
            parameters.setPlatform(getString(R.string.platform_android));
            parameters.setUserId(application.getAccount());
            String content = etContent.getText().toString().trim();
            parameters.setContent(content.trim());
            parameters.setLocation(tvLocation.getText().toString().trim());
            parameters.setLatitude(mLatitude + "");
            parameters.setLongitude(mLongitude + "");
            String url;
            try {
                url = new StringBuilder().append(AddressManager.getInstance().getAddress())
                        .append("?").append(getString(R.string.command))
                        .append("=").append(parameters.getCommand())
                        .append("&").append(getString(R.string.data))
                        .append("=").append(URLEncoder.encode(new Gson().toJson(parameters), "UTF-8"))
                        .toString();
            } catch (Exception e) {
                e.printStackTrace();
                return;
            }
            request = NoHttp.createStringRequest(url, RequestMethod.POST);
//            request.setContentType("multipart/form-data; boundary=alamofire.boundary.8479ba3fabe53e37");
            request.add(getString(R.string.command), parameters.getCommand());
            request.add(getString(R.string.platform), parameters.getPlatform());
            request.add("userId", parameters.getUserId());
            request.add("content", parameters.getContent());
            request.add("location", parameters.getLocation());
            request.add("longitude", parameters.getLongitude());
            request.add("latitude", parameters.getLatitude());
            if (MyBitmap.tempSelectBitmap.size() > 0){
                List<Binary> binaries = new ArrayList<>();
                for (MyAlbum album : MyBitmap.tempSelectBitmap) {
                    Logger.i("Edit dynamics picture path " + album.getmPath());
                    File file = new File(album.getmPath());
                    BasicBinary fileBinary = new FileBinary(file);
                    binaries.add(fileBinary);
                }
                request.add("picFileBinary", binaries);
            }
            request.setCancelSign(toString());
            WebServerManager.getInstance().add(this, request, new ResponseCallback<String>() {
                        @Override
                        public void onSucceed(int what, Response<String> response) {
                            String bean = response.get();
                            BasicBean basicBean = new Gson().fromJson(bean, BasicBean.class);

                            if (basicBean == null) {
                                return;
                            }

                            if (basicBean.isSuccess()) {
                                Snackbar.make(llParent, "发表成功", Snackbar.LENGTH_SHORT).show();
                                MyBitmap.tempSelectBitmap.clear();
                                if (null != mAlbumFiles) {
                                    mAlbumFiles.clear();
                                }
                                startActivity(new Intent(EditActivity.this, MainActivity.class)
                                        .putExtra(getString(R.string.tab_title),
                                        getString(R.string.tab_dynamics_title)));
                            } else {
                                Snackbar.make(llParent, "发表失败", Snackbar.LENGTH_SHORT).show();
                            }
                        }

                        @Override
                        public void onFailed(int what, Object tag, Exception exception, long networkMillis) {

                        }
                    },
                    COMMIT_DYNAMICS_WHAT, true, true, true);

        } else {
            ToastUtils.showShort(getString(R.string.network_error));
        }

    }

    private void initAdapter() {
        gridPicAdapter = new GridPicAdapter(this);
        gridPicAdapter.updateData();
        gvPics.setAdapter(gridPicAdapter);
        gvPics.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            public void onItemClick(AdapterView<?> parent, View view, int position,
                                    long id) {
                if (position == MyBitmap.tempSelectBitmap.size()) {

                        Album.image(EditActivity.this)
                                .multipleChoice()
                                .requestCode(200)
                                .camera(true)
                                .columnCount(3)
                                .selectCount(9)
                                .checkedList(mAlbumFiles)
                                .widget(Widget.newDarkBuilder(EditActivity.this)
                                        .title("图片")
                                        .statusBarColor(ContextCompat.getColor(application, R.color.colorPrimary))
                                        .toolBarColor(ContextCompat.getColor(application, R.color.colorPrimary))
                                        .navigationBarColor(ContextCompat.getColor(application, android.R.color.black)) // Android5.0+的虚拟导航栏颜色。
                                        .mediaItemCheckSelector(Color.WHITE, Color.GREEN) // 图片或者视频选择框的选择器。
                                        .bucketItemCheckSelector(
                                                ContextCompat.getColor(application, R.color.colorPrimary),
                                                ContextCompat.getColor(application, R.color.colorPrimary)) // 切换文件夹时文件夹选择框的选择器。
                                        .build())

                                .onResult(new Action<ArrayList<AlbumFile>>() {
                                    @Override
                                    public void onAction(int requestCode, @NonNull ArrayList<AlbumFile> result) {
                                        if (null != result) {
                                            mAlbumFiles = result;
                                            List<MyAlbum> tempList = new ArrayList<>();

                                            for (AlbumFile file : result) {
                                                tempList.add(new MyAlbum(file));
                                            }
                                            MyBitmap.tempSelectBitmap = (ArrayList<MyAlbum>) tempList;
                                            gridPicAdapter.updateData();
                                        }
                                    }
                                })
                                .onCancel(new Action<String>() {
                                    @Override
                                    public void onAction(int requestCode, @NonNull String result) {
//                                ToastUtils.showShort("取消了");
                                    }
                                })

                                .start();
                } else {
                    Album.galleryAlbum(EditActivity.this)
                            .requestCode(2) // 请求码，会在listener中返回。
                            .checkedList(mAlbumFiles) // 要浏览的图片列表：ArrayList<String>。
                            .navigationAlpha(80) // Android5.0+的虚拟导航栏的透明度。
                            .checkable(true) // 是否有浏览时的选择功能。
                            .currentPosition(position)
                            .widget(Widget.newLightBuilder(EditActivity.this)
                                    .title("已选")
                                    .mediaItemCheckSelector(Color.WHITE, Color.GREEN) // 图片或者视频选择框的选择器。
                                    .bucketItemCheckSelector(
                                            ContextCompat.getColor(application, R.color.colorPrimary),
                                            ContextCompat.getColor(application, R.color.colorPrimary)) // 切换文件夹时文件夹选择框的选择器。
                                    .build())
                            .onResult(new Action<ArrayList<AlbumFile>>() {
                                @Override
                                public void onAction(int requestCode, @NonNull ArrayList<AlbumFile> result) {
                                    if (null != result) {
                                        mAlbumFiles = result;
                                        List<MyAlbum> tempList = new ArrayList<>();

                                        for (AlbumFile file : result) {
                                            tempList.add(new MyAlbum(file));
                                        }
                                        MyBitmap.tempSelectBitmap = (ArrayList<MyAlbum>) tempList;
                                        gridPicAdapter.updateData();
                                    }
                                }
                            })
                            .onCancel(new Action<String>() {
                                @Override
                                public void onAction(int requestCode, @NonNull String result) {
                                    // 用户取消了操作。
                                }
                            })
                            .start();
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                launchExit();
//                if (!TextUtils.isEmpty(etContent.getText().toString())
//                        || MyBitmap.tempSelectBitmap.size() > 0) {
//                    launchExit();
//                } else {
//                    if (null != mAlbumFiles) {
//                        mAlbumFiles.clear();
//                    }
//                    finish();
//                }
                break;

            case R.id.tv_edit_release:
                if (!checkForm()) return;
                commitRequest();
                break;

            case R.id.tv_location:
                TimeMapActivity.start(this, TIME_MAP_REQUEST_CODE,
                        getString(R.string.map_flag_dynamics),
                        tvLocation.getText().toString());
                break;

            default:
                break;
        }
    }

    private boolean checkForm() {
        if (TextUtils.isEmpty(etContent.getText().toString().trim())) {
            ToastUtils.showShort("请添加你的内容");
            return false;
        }

        if (TextUtils.isEmpty(tvLocation.getText().toString().trim())) {
            ToastUtils.showShort("请添加你的地点");
            return false;
        }
        return true;
    }

    private void launchExit() {
        final Window window = this.getWindow();
        attributes = window.getAttributes();
        attributes.alpha = 0.5f;
        window.setAttributes(attributes);
        exitEditPW = new ExitEditPW(this, llParent);
        exitEditPW.setTip("退出此次编辑？");
        exitEditPW.setLeft(getString(R.string.btn_think_about));
        exitEditPW.setRight(getString(R.string.btn_confirm));
        exitEditPW.setOnItemClickListener(new BasePW.OnItemClickListener<String>() {
            @Override
            public void onItemClick(int type, String result) {
                MyBitmap.tempSelectBitmap.clear();
                if (null != mAlbumFiles) {
                    mAlbumFiles.clear();
                }
                finish();
            }
        });
        exitEditPW.showAtLocation(llParent, Gravity.CENTER, 0, 0);
        exitEditPW.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                attributes.alpha = 1.0f;
                window.setAttributes(attributes);
            }
        });
    }

    private void launchDelete(String deleteId) {
        final Window window = this.getWindow();
        attributes = window.getAttributes();
        attributes.alpha = 0.5f;
        window.setAttributes(attributes);
        deletePW = new DeletePW(this, llParent, deleteId, getString(R.string.pw_delete_pic_title));
        deletePW.setOnItemClickListener(new BasePW.OnItemClickListener<String>() {
            @Override
            public void onItemClick(int type, String deleteId) {
                // 删除图片
                if (Integer.parseInt(deleteId) >= 0) {
                    MyBitmap.tempSelectBitmap.remove(Integer.parseInt(deleteId));
                    if (null != mAlbumFiles) {
                        if (Integer.parseInt(deleteId) < mAlbumFiles.size()) {
                            mAlbumFiles.remove(Integer.parseInt(deleteId));
                        }
                    }
                    ToastUtils.showShort(R.string.delete_success);
                    gridPicAdapter.updateData();
                }

            }
        });
        deletePW.showAtLocation(llParent, Gravity.CENTER, 0, 0);
        deletePW.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                attributes.alpha = 1.0f;
                window.setAttributes(attributes);
            }
        });
    }

    // 权限回调监听
    private PermissionListener listener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
            if (requestCode == PICTURE_PERMISSION_REQUEST_CODE) {
                // 表示读写的权限申请通过, 创建根目录
                application.initDir();
                Album.image(EditActivity.this)
                        .multipleChoice()
                        .requestCode(200)
                        .camera(true)
                        .columnCount(3)
                        .selectCount(6)
                        .checkedList(mAlbumFiles)
                        .widget(Widget.newDarkBuilder(EditActivity.this)
                                .title("图片")
                                .statusBarColor(ContextCompat.getColor(application, R.color.colorPrimary))
                                .toolBarColor(ContextCompat.getColor(application, R.color.colorPrimary))
                                .navigationBarColor(ContextCompat.getColor(application, android.R.color.black))
                                .mediaItemCheckSelector(Color.WHITE, Color.GREEN) // 图片或者视频选择框的选择器。
                                .bucketItemCheckSelector(
                                        ContextCompat.getColor(application, R.color.colorPrimary),
                                        ContextCompat.getColor(application, R.color.colorPrimary)) // 切换文件夹时文件夹选择框的选择器。
                                .build())

                        .onResult(new Action<ArrayList<AlbumFile>>() {
                            @Override
                            public void onAction(int requestCode, @NonNull ArrayList<AlbumFile> result) {
                                if (null != result) {
                                    mAlbumFiles = result;
                                    List<MyAlbum> tempList = new ArrayList<>();

                                    for (AlbumFile file : result) {
                                        tempList.add(new MyAlbum(file));
                                    }
                                    MyBitmap.tempSelectBitmap = (ArrayList<MyAlbum>) tempList;
                                    gridPicAdapter.updateData();
                                }
                            }
                        })
                        .onCancel(new Action<String>() {
                            @Override
                            public void onAction(int requestCode, @NonNull String result) {
//                                ToastUtils.showShort("取消了");
                            }
                        })

                        .start();
            } else if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
                // 表示定位的权限申请通过
                createLocationRequest();
            }
        }

        @Override
        public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
            if (requestCode == PICTURE_PERMISSION_REQUEST_CODE) {
                // 即使是用户选择了不在询问还是会toast该提示语
//                ToastUtils.showShort("请开启内部存储的读写权限");

            }
            // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权
            if (AndPermission.hasAlwaysDeniedPermission(EditActivity.this, deniedPermissions)) {
//                // 第一种：用默认的提示语。
                AndPermission.defaultSettingDialog(EditActivity.this, DENIED_PERMISSION_REQUEST_CODE).show();
//
            }
        }
    };

    protected void createLocationRequest() {

        tvLocation.setText("定位中...");

        // 初始化请求
        locationRequest = new AMapLocationClient(getApplicationContext());

        // 设置回调监听
        locationRequest.setLocationListener(this);

        // 初始化参数集
        AMapLocationClientOption mLocationOption = new AMapLocationClientOption();

        // 高精度定位模式，省电模式， 仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);

        // 是否返回地址信息
        mLocationOption.setNeedAddress(true);

        // 设置重定位时间间隔
        mLocationOption.setInterval(5000);

        mLocationOption.setOnceLocation(true);

        // 设置参数集
        locationRequest.setLocationOption(mLocationOption);

        locationRequest.startLocation();
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation == null || aMapLocation.getErrorCode() != 0) {
            Logger.e("Amap location Error");
            ToastUtils.showShort("定位失败");
            return;
        }

        Logger.i("Current user postion is lat : " + aMapLocation.getLatitude() +
                " and lon : " + aMapLocation.getLongitude());
        curLocation = aMapLocation.getPoiName();
        mLatitude = aMapLocation.getLatitude();
        mLongitude = aMapLocation.getLongitude();
        tvLocation.setText(aMapLocation.getPoiName() + "");
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {

            case DENIED_PERMISSION_REQUEST_CODE:
                // 用户从设置中回来，无论有没有开启所需要的权限
//                ToastUtils.showShort("从设置中回来");
                break;

            case TIME_MAP_REQUEST_CODE:
                if (null != data) {
                    mLatitude = data.getDoubleExtra(Constant.LATITUDE, 0.0d);
                    mLongitude = data.getDoubleExtra(Constant.LONGITUDE, 0.0d);
                    curLocation = data.getStringExtra(Constant.LOCATION);
                    if (!TextUtils.isEmpty(curLocation)) {
                        tvLocation.setText(curLocation);
                    }
                }
                break;

            default:
                break;
        }
    }

    class GridPicAdapter extends BaseAdapter {

        private Context mContext;
        private LayoutInflater mInflater;
        private List<MyAlbum> myAblums;

        private int selectedPos;
        private boolean shape;

        public GridPicAdapter(Context context) {
            mContext = context;
            mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        public void updateData() {
            myAblums = MyBitmap.tempSelectBitmap;
            notifyDataSetChanged();
//            loading();
        }

        public boolean isShape() {
            return shape;
        }

        public void setShape(boolean shape) {
            this.shape = shape;
        }

        public int getSelectedPos() {
            return selectedPos;
        }

        public void setSelectedPos(int selectedPos) {
            this.selectedPos = selectedPos;
        }

        @Override
        public int getCount() {
            if (myAblums.size() == 6) {
                return 6;
            }
            return (myAblums.size() + 1);
        }

        @Override
        public MyAlbum getItem(int position) {
            return myAblums.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = mInflater.inflate(R.layout.item_pic_grid, parent, false);
                holder.ivPic = convertView.findViewById(R.id.iv_publish_grid_pic);
                holder.ivDelete = convertView.findViewById(R.id.iv_publish_grid_pic_delete);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            if (((MyGridView) parent).isOnMeasure) {
                // 如果是onMeasure调用的就立即返回
                return convertView;
            }

            if (position == myAblums.size()) {
                // 表示最后一个元素
                holder.ivPic.setImageResource(R.drawable.iv_publish_add_pic);
                holder.ivDelete.setVisibility(View.GONE);
                if (position == 6) {
                    holder.ivPic.setVisibility(View.GONE);
                } else {
                    holder.ivPic.setVisibility(View.VISIBLE);
                }
            } else {
                int size = ScreenUtils.dip2px(77);
                PicassoImageLoader.loadImageViewSize(mContext,
                        MyBitmap.tempSelectBitmap.get(position).getmPath(),
                        size,
                        size,
                        R.drawable.iv_default_92_68,
                        R.drawable.iv_default_92_68,
                        toString(), holder.ivPic);
                holder.ivDelete.setVisibility(View.VISIBLE);
            }

            holder.ivDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (deletePW == null || !deletePW.isShowing()) {
                        launchDelete(position + "");
                    } else {
                        return;
                    }
                }
            });

            return convertView;
        }

        class ViewHolder {
            RoundedImageView ivPic;
            ImageView ivDelete;
        }

    }

    @Override
    public void onSucceed(int what, Response<BasicBean> response) {
        BasicBean basicBean = response.get();
        if (basicBean == null) return;
        if (basicBean.isSuccess()) {
            // TODO: 2017/11/1
        } else {
            ToastUtils.showShort(basicBean.getMsg());
        }
    }

    @Override
    public void onBackPressed() {
//        if (!TextUtils.isEmpty(etContent.getText().toString())
//                || MyBitmap.tempSelectBitmap.size() > 0) {
            launchExit();
//        } else {
//            super.onBackPressed();
//        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        locationRequest.stopLocation();

        if (null != exitEditPW) {
            exitEditPW.dismiss();
            exitEditPW = null;
        }
        if (null != deletePW) {
            deletePW.dismiss();
            deletePW = null;
        }

    }

}
